package com.intelligentpension.kotlinbluetoothprint.activity

import android.annotation.SuppressLint
import android.bluetooth.*
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.intelligentpension.kotlinbluetoothprint.R
import com.intelligentpension.kotlinbluetoothprint.adapter.BluetoothItemAdapter
import com.intelligentpension.kotlinbluetoothprint.bean.BluethBean
import com.intelligentpension.kotlinbluetoothprint.utils.BluetoothDiscoverBordcast
import com.intelligentpension.kotlinbluetoothprint.utils.ConstantUtils
import com.intelligentpension.kotlinbluetoothprint.utils.ThreadUtils
import java.lang.reflect.Method


class BluetoothListActivity : AppCompatActivity() {
    private lateinit var mRecycler: RecyclerView
    private lateinit var mItemAdapter: BluetoothItemAdapter
    private lateinit var bordcast: BluetoothDiscoverBordcast
    private var mList: MutableList<BluethBean> = ArrayList()
    private var mDveList: MutableList<BluetoothDevice> = ArrayList()
    private lateinit var mBlue: BluetoothAdapter

    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bluetooth_list)
        mBlue = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        mRecycler = findViewById<RecyclerView>(R.id.recycler)
        var layoutManager = LinearLayoutManager(this)
        mRecycler.layoutManager = layoutManager
        mItemAdapter = BluetoothItemAdapter(R.layout.blueth_item, mList)
        mRecycler.adapter = mItemAdapter

        //开始查找蓝牙
        scanBlue()

        //点击连接蓝牙
        mItemAdapter.setOnItemClickListener { _, _, position ->
            var bluethDevice = mList[position]
            var dev = bluethDevice.dev

            //TODO:蓝牙自动配对
            // 自动配对就是通过反射去调用 BluetoothDevice 的 createBond 方法
            if (dev.bondState != BluetoothDevice.BOND_BONDED) {
                val createBondMethod: Method = BluetoothDevice::class.java.getMethod("createBond")
                createBondMethod.invoke(dev)
            } else {
                //配对完成的蓝牙直接连接
                connectBluetooth(dev)
                //TODO:其实这里不用连接,直接返回dve的地址数值即可
//                var intent = Intent()
//                intent.putExtra("name", dev.name + "")
//                intent.putExtra("address", dev.address + "")
//                setResult(10, intent)
//                this@BluetoothListActivity.finish()
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun scanBlue() {

        //获取当前已经配对的蓝牙
        var bondedDevices = mBlue.bondedDevices

        for (dve in bondedDevices) {
            if (!mDveList.contains(dve)) {
                mDveList.add(dve)
                var bean = BluethBean(dve, dve.name, dve.address)
                mList.add(bean)
            }
        }
        mItemAdapter.notifyDataSetChanged()

        //开启广播
        bordcast = BluetoothDiscoverBordcast(this, object : BluetoothDiscoverBordcast.Listener {
            override fun foundDev(dev: BluetoothDevice?) {
                if (dev != null && !mDveList.contains(dev)) {
                    mDveList.add(dev)
                    var bean = BluethBean(dev, dev.name, dev.address)
                    mList.add(bean)
                    mItemAdapter.notifyDataSetChanged()
                }
            }

            //当点击条目的时候,配对会监听配完后的连接状态
            override fun connectState(dev: BluetoothDevice) {
                when (dev.bondState) {
                    //正在配对
                    BluetoothDevice.BOND_BONDING -> {
                        ToastUtils.show("正在配对")
                    }
                    //配对结束
                    BluetoothDevice.BOND_BONDED -> {
                        ToastUtils.show("配对成功")
                        //检查是否已经连接上去了
                        if (dev.bondState == BluetoothDevice.BOND_BONDED) {
                            var intent = Intent()
                            intent.putExtra("name", dev.name + "")
                            intent.putExtra("address", dev.address + "")
                            setResult(10, intent)
                            finish()
                        }
                    }
                    //取消配对
                    BluetoothDevice.BOND_NONE -> {
                        ToastUtils.show("取消配对")
                    }
                }
            }
        })

        //设置蓝牙可以被发现
        mBlue.startDiscovery()

    }

    //连接蓝牙
    @SuppressLint("MissingPermission")
    private fun connectBluetooth(dev: BluetoothDevice) {
        ThreadUtils.executeSubThread {
            try {
                var socket = dev.createRfcommSocketToServiceRecord(ConstantUtils.BluetoothUUID)
                socket.connect()
                if (socket.isConnected) {
                    ThreadUtils.executeMainThread {
                        ToastUtils.show("连接Ok了")
                        //检查是否已经连接上去了
                        if (dev.bondState == BluetoothDevice.BOND_BONDED) {
                            var intent = Intent()
                            intent.putExtra("name", dev.name + "")
                            intent.putExtra("address", dev.address + "")
                            setResult(10, intent)
                            this@BluetoothListActivity.finish()
                        }
                    }
                }
            } catch (e: Exception) {

            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //注销当前的广播
        unregisterReceiver(bordcast)
    }
}